package com.jdpc.weparty.controller

import com.jdpc.weparty.component.ServerConfig
import com.jdpc.weparty.controller.vo.*
import com.jdpc.weparty.entity.Activity
import com.jdpc.weparty.entity.ActivityType
import com.jdpc.weparty.entity.User
import com.jdpc.weparty.service.activity.generateActivityInfo
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.system.SystemProperties
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*
import org.springframework.web.multipart.MultipartFile
import java.io.File


@RestController
@RequestMapping("/test")
class TestController {
    //    @GetMapping("/activities")
//    fun test(@RequestParam("order") order: String, @RequestParam("page") page: Int, @RequestParam("size") size: Int): JsonBody<List<ActivityInfoVo>> {
//
//    }
    private val host = "172.23.142.103:8080"
    @Autowired
    lateinit var serverConfig: ServerConfig

    private var localPath = SystemProperties.get("user.dir")

    @PostMapping("/users/{id}/avatar")
    fun loadUserPic(@PathVariable("id") uId: Int, @RequestParam("file", required = false) file: MultipartFile?): ResponseEntity<*> {
        file?.let {
            if (!file.isEmpty) {
                val fileName = file.originalFilename
                println("fileName:$fileName")
                println(file.name)
                var path: String? = null
                var type: String? = null
                type = if (fileName!!.indexOf(".") != -1) fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length) else null
                if (type != null) {
                    if ("GIF" == type.toUpperCase() || "PNG" == type.toUpperCase() || "JPG" == type.toUpperCase()) { // 项目在容器中实际发布运行的根路径

                        val trueFileName = "user$uId.$type"
                        // 设置存放图片文件的路径
                        path = "$localPath/src/main/resources/static/avatar/$trueFileName"
                        file.transferTo(File(path))

                    } else {
                        return ResponseEntity.ok(JsonBody(-1, "图片格式不合要求", ""))
                    }
                } else {
                    return ResponseEntity.ok(JsonBody(-1, "未发现图片格式后缀", ""))
                }
            } else {
                return ResponseEntity.ok(JsonBody(-1, "未上传图片", ""))
            }
        } ?: return ResponseEntity.ok(JsonBody(-1, "未上传图片", ""))


        return ResponseEntity.ok(JsonBody(0, "成功", ""))
    }

    //按照id请求用户信息
    @GetMapping("/users/{id}")
    fun getUser(@PathVariable("id") uId: Int): ResponseEntity<*> {
        return ResponseEntity.ok(JsonBody(0, "", UserVo().apply {
            this.id = 0
            this.age = 15
            this.avatar = "http://gushichen.gitee.io/img/avator-chase.jpg"
            this.gender = "男"
            this.phoneNumber = "185xxxxxxx"
            this.userName = "adsb"
            this.userNumber = "3018xxxxxx"
        }))
    }

    //修改用户信息
    @PostMapping("/users/{id}")
    fun changeUser(@PathVariable("id") uId: Int, @RequestBody info: UserVo): ResponseEntity<*> {
        return ResponseEntity.ok(JsonBody(0, "成功", info))
    }

    //获取id用户参加的所有活动
    @GetMapping("/users/{id}/joined")
    fun getJoinedActivities(@PathVariable("id") id: Int, @RequestParam("state") state: String): ResponseEntity<*> {
        val l1 = listOf<Activity4JoinerVo>(generateActivity4JoinerVo(1, null), generateActivity4JoinerVo(2, null))
        val l2 = listOf<Activity4JoinerVo>(generateActivity4JoinerVo(3, true), generateActivity4JoinerVo(4, true), generateActivity4JoinerVo(5, true))
        val l3 = listOf<Activity4JoinerVo>(generateActivity4JoinerVo(6, false), generateActivity4JoinerVo(7, false))

        var list = when (state) {
            "passing" -> {
                l1
            }
            "passed" -> {
                l2
            }
            "deny" -> {
                l3
            }
            else -> {
                listOf<Activity4JoinerVo>().toMutableList().apply {
                    addAll(l1)
                    addAll(l2)
                    addAll(l3)
                }
            }
        }
        return ResponseEntity.ok(JsonBody(0, "成功", list))
    }

    @GetMapping("/users/{id}/published")
    fun getPublishedActivities(@PathVariable("id") id: Int, @RequestParam("state") state: String): ResponseEntity<*> {
        val l1 = listOf<Activity4PublisherVo>(generateActivity4PublisherVo(11, null), generateActivity4PublisherVo(12, null))
        val l2 = listOf<Activity4PublisherVo>(generateActivity4PublisherVo(13, true), generateActivity4PublisherVo(14, true), generateActivity4PublisherVo(15, true))
        val l3 = listOf<Activity4PublisherVo>(generateActivity4PublisherVo(16, false), generateActivity4PublisherVo(17, false))

        var list = when (state) {
            "checking" -> {
                l1
            }
            "checked" -> {
                l2
            }
            "deny" -> {
                l3
            }
            else -> {
                listOf<Activity4PublisherVo>().toMutableList().apply {
                    addAll(l1)
                    addAll(l2)
                    addAll(l3)
                }
            }
        }
        return ResponseEntity.ok(JsonBody(0, "成功", list))
    }

    @PostMapping("/users/")
    fun register(@RequestBody userVo: UserVo): ResponseEntity<*> {
        return ResponseEntity.ok(JsonBody(0, "", userVo))
    }

    private val e = User().apply {
        id = 1
        this.userName = "管理员甲"
        this.gender = "男"
        this.phoneNumber = "18526xxxxxx"
        this.userNumber = "3018xxxxxx"
        this.age = 20
    }
    private val p = User().apply {
        id = 2
        this.userName = "发布者甲"
        this.gender = "女"
        this.phoneNumber = "185xxxxxxxx"
        this.userNumber = "3018xxxxxx"
        this.age = 20
    }
    private val j1 = User().apply {
        id = 3
        this.userName = "参与者1"
        this.gender = "女"
        this.phoneNumber = "2332xxxxxxx"
        this.userNumber = "3233xxxxxx"
        this.age = 223
    }
    private val j2 = User().apply {
        id = 4
        this.userName = "参与者2"
        this.gender = "男"
        this.phoneNumber = "158xxxxxxx"
        this.userNumber = "3019xxxxxx"
        this.age = 19
    }

    private val activities = listOf(Activity().apply {
        this.location = "221宿舍"
        this.activityCode = "#awenj2n#"
        this.activityProfile = "LOOOOOOOOLLLL"
        this.activityName = "LOL战斗之夜"
        this.id = 1
        this.startTime = 1220
        this.endTime = 1540
        this.publishTime = 1200
        this.publisher = p
        this.examiner = e
        this.activityPic = "http://${host}/banner/testActivity1.jpg"
    }, Activity().apply {
        this.location = "青年湖底"
        this.activityCode = "#qwheu2h2e#"
        this.activityProfile = "裴仁杰相亲啦相亲啦~"
        this.activityName = "裴仁杰相亲活动"
        this.id = 2
        this.startTime = 0
        this.endTime = 24 * 60 * 60 * 365 * 4
        this.publishTime = 0
        this.publisher = p
        this.examiner = e
    })

    //根据id获取活动信息
    @GetMapping("/activities/{id}")
    fun getActivity(@PathVariable("id") id: Int): ResponseEntity<*> {
        return if (id in 1..2) {
            val aIf = ActivityInfoVo(activities[id], 10)
            ResponseEntity.ok(JsonBody(0, "成功", aIf))

        } else {
            ResponseEntity.badRequest().body(JsonBody(-1, "没有id=${id}的活动", Any()))
        }
    }

    //查看某活动所有参与者
    @GetMapping("/activities/{id}/joiners")
    fun getJoiners(@PathVariable("id") id: Int, @RequestParam page: Int, @RequestParam size: Int): ResponseEntity<*> {

//        var result = signUpActivityService.getUserForm(id, true, pageable)
//        return ResponseEntity.ok(JsonBody(0, "成功", result.content.map {
//            UserVo().apply {
//                setInfo(it)
//            }
//        }))
        return if (id in 1..2) {
            ResponseEntity.ok(JsonBody(1, "成功", listOf<UserVo>(UserVo().apply {
                setInfo(j1)
            }, UserVo().apply {
                setInfo(j2)
            })))
        } else {
            ResponseEntity.badRequest().body(JsonBody(-1, "没有id=${id}的活动", Any()))
        }
    }

    //为某活动添加一条参加申请
    @PostMapping("/activities/{activityId}/joiners/{userId}")
    fun addApply(@PathVariable("activityId") aId: Int, @PathVariable("userId") uId: Int): ResponseEntity<*> {
        return ResponseEntity.ok(JsonBody(0, "成功", Any()))
    }

    //提供主页活动推荐
    @GetMapping("/activities/home")
    fun getActivitiesByOrder(@RequestParam order: String, @RequestParam page: Int, @RequestParam size: Int): ResponseEntity<*> {
//        var page = when (order) {
////            "default" -> {
////
////            }
//            "hotest" -> {
//                //按活动开始时间升序排列
//                val pageable = PageRequest.of(page, size, Sort.Direction.ASC, "a_start")
//                activityService.getAllActivity(pageable)
//
//            }
//            "latest" -> {
//                //按活动开始时间升序排列
//                val pageable = PageRequest.of(page, size, Sort.Direction.ASC, "a_start")
//                activityService.getAllActivity(pageable)
//            }
//            else -> {
//                val pageable = PageRequest.of(page, size)
//                activityService.getAllActivity(pageable)
//            }
//        }
//        return ResponseEntity.ok(JsonBody(0, "成功", page.content.map {
//            ActivityInfoVo(it, signUpActivityService.getUserForm(it.id, true).size)
//        }))
        if (order == "default" || order == "hotest" || order == "latest") {
            return ResponseEntity.ok(JsonBody(0, "成功", activities.map {
                ActivityInfoVo(it, 10)
            }))
        } else {
            return ResponseEntity.badRequest().body(JsonBody(-1, "无法根据order=${order}排序", Any()))
        }
    }

    //根据名字检索活动
    @GetMapping("/activities")
    fun getActivitiesByName(@RequestParam name: String/*, @RequestParam kind: ActivityType*/): ResponseEntity<*> {
        val result: MutableList<ActivityInfoVo> = arrayListOf()
        for (i in 0..1) {
            if (activities[i].activityName.contains(name)) {
                result.add(ActivityInfoVo(activities[i], 10))
            }
        }
        return ResponseEntity.ok(JsonBody(0, "成功", result))
    }

    //添加活动
    @PostMapping("/activities")
    fun addNewActivity(@RequestBody info: ActivityInfoVo): ResponseEntity<*> {
        val activityInfo = generateActivityInfo(info)
        return ResponseEntity.ok(JsonBody(0, "成功", Any()))
//        val examiner = userService.pickOneExaminer()
//        publisher?.let {
//            activityService.publishActivity(activityInfo, it, examiner)
//            return ResponseEntity.ok(JsonBody(0, "成功", Any()))
//        } ?: return ResponseEntity.badRequest().body(JsonBody(-1, "未找到发布者", Any()))
    }

    //修改活动信息
    @PutMapping("/activities/{id}")
    fun changeActivityInfo(@RequestBody info: ActivityInfoVo): ResponseEntity<*> {
        val activityInfo = generateActivityInfo(info)
//        activityService.changeActivityInfo(info.activityId, activityInfo)
        return ResponseEntity.ok(JsonBody(0, "成功", Any()))
    }

//    @PostMapping("/activities/{id}/banner")
//    fun uploadBanner(@PathVariable("id") aId: Int, @RequestParam("file", required = false) file: MultipartFile?): ResponseEntity<*> {
//        file?.let {
//            return ResponseEntity.ok(JsonBody(0, "成功", pictureService.savePicture(it, aId)))
//
//        }
//        return ResponseEntity.badRequest().body(JsonBody(-1, "失败", Any()))
//    }

    private fun generateActivity4PublisherVo(id: Int, checked: Boolean?): Activity4PublisherVo {
        return Activity4PublisherVo(ActivityInfoVo(Activity().apply {
            this.activityType = ActivityType.PLAY
            this.publishTime = System.currentTimeMillis()
            this.checked = checked
            this.startTime = 1200
            this.endTime = 1340
            this.id = id
            this.activityName = "name$id"
            this.activityProfile = "profile$id"
            this.examiner = User().apply {
                this.userName = "examiner"
            }
            this.publisher = User().apply {
                this.userName = "publisher"
            }
            this.activityCode = id.toString()
            this.location = "55教"
        }, 10), checked)
    }

    private fun generateActivity4JoinerVo(id: Int, passed: Boolean?): Activity4JoinerVo {
        return Activity4JoinerVo(ActivityInfoVo(Activity().apply {
            this.activityType = ActivityType.PLAY
            this.publishTime = System.currentTimeMillis()
            this.checked = true
            this.startTime = 1200
            this.endTime = 1340
            this.id = id
            this.activityName = "name$id"
            this.activityProfile = "profile$id"
            this.examiner = User().apply {
                this.userName = "examiner"
            }
            this.publisher = User().apply {
                this.userName = "publisher"
            }
            this.activityCode = id.toString()
            this.location = "55教"
        }, 10), passed)
    }
}